package com.cqw.auth.handlers;

import com.alibaba.fastjson.JSON;
import com.cqw.common.BaseResponse;
import com.cqw.common.HttpStatus;
import com.cqw.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-16 16:34
 * @Description: 认证失败处理类 返回未授权
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {


    private static final long serialVersionUID = -8320094518343985491L;

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = String.format("请求访问资源：%s,认证失败，无法访问系统资源", httpServletRequest.getRequestURI());
        ServletUtils.sendString(httpServletResponse, JSON.toJSONString(BaseResponse.error(code, msg)));
    }
}
